package com.sunlands.zlcx.usercenter.service.status;

import com.sunlands.zlcx.usercenter.client.SocketService;
import com.sunlands.zlcx.usercenter.client.bean.ShareMsgParamVO;
import com.sunlands.zlcx.usercenter.constant.LearningStatus;
import com.sunlands.zlcx.usercenter.constant.RedisKeyConst;
import com.sunlands.zlcx.usercenter.constant.YN;
import com.sunlands.zlcx.usercenter.domain.LearnContentDO;
import com.sunlands.zlcx.usercenter.domain.UsersLearnTimingDO;
import com.sunlands.zlcx.usercenter.domain.UsersTargetRelationDO;
import com.sunlands.zlcx.usercenter.service.status.common.AbstractStudyStatus;
import com.sunlands.zlcx.usercenter.util.BeanPropertiesUtil;
import com.sunlands.zlcx.usercenter.util.CalendarUtil;
import com.sunlands.zlcx.usercenter.util.DateUtil;
import com.sunlands.zlcx.usercenter.vo.LeaveMsgVO;
import com.sunlands.zlcx.usercenter.vo.UserMonthLearnVO;
import com.sunlands.zlcx.usercenter.vo.UsersStudyInfoVO;
import com.sunlands.zlcx.usercenter.vo.UsersVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static com.sunlands.zlcx.usercenter.constant.MessageType.TIME_LEARN_ROOM_TAKE_SEAT_NOTICE;

/**
 * @author gaoyanfeng
 * @create 2019-04-28 9:50
 **/
@Component
@Slf4j
public class OrdernaryStartLearn extends AbstractStudyStatus implements BeanPropertiesUtil {

    @Autowired
    private SocketService socketService;
    @Resource(name = "commonTaskExecutor")
    private AsyncTaskExecutor commonTaskExecutor;

    @Override
    public void handle(UsersStudyInfoVO studyInfo, UsersTargetRelationDO targetRelation) {

        Long userId = targetRelation.getUserId();
        checkTimingPeriod(studyInfo, userId);
        redisTemplate.opsForValue().set(RedisKeyConst.getStudyName(userId), studyInfo.getStudyInfoName());
        Date startTime = DateUtil.covertTime(new Date());
        usersService.updateStatus(userId, LearningStatus.LEARN_TIMING.getCode(), startTime, null, null);
        if (Objects.nonNull(studyInfo.getContentId())) {
            LearnContentDO contentDO = usersLearnService.findOne(studyInfo.getContentId());
            if (!contentDO.getUserId().equals(userId)) {
                throw new IllegalArgumentException("该学习内容不属于当前用户 userId = " + studyInfo.getUserId());
            }
            contentDO.setStatus(LearningStatus.LEARN_TIMING.getCode());
            usersLearnService.update(contentDO);
            if (contentDO.getModel().intValue() == LearnContentDO.ModelEnum.valid.code.intValue()) {
                usersLearnService.schedeledTask(contentDO, (contentDO.getMinutes() - 5) * 60L);
            }

        }
        studyInfo.setUserSetTime(null);

        UsersLearnTimingDO usersLearnTimingDO = new UsersLearnTimingDO();
        copyNonNullProperties(studyInfo, usersLearnTimingDO);
        usersLearnTimingDO.setTargetId(studyInfo.getTargetId());
        usersLearnTimingDO.setStatus(YN.NO.getCode());
        usersLearnTimingDO.setLearnName(studyInfo.getStudyInfoName());
        usersLearnTimingDO.setTargetId(targetRelation.getTargetId());
        Date countTime = CalendarUtil.getDateHoursBefore(startTime, 3);
        usersLearnTimingDO.setCountTime(countTime);
        usersLearnTimingDO.setWeek(CalendarUtil.getWeek(countTime));
        usersLearnTimingDO.setStartTime(startTime);
        usersLearnTimingDO.setType(UsersLearnTimingDO.TypeEnums.ORDERNARY_COUNT_TIME.code);
        UserMonthLearnVO.FriendLearnInfo learnInfo = usersStudyService.getLearnRankList(userId, 0).stream().filter(friendLearnInfo -> friendLearnInfo.getFriendId().equals(userId)).findFirst().orElse(null);
        usersLearnTimingDO.setStartSort(Objects.nonNull(learnInfo) ? learnInfo.getIndex() : 1);
        usersLearnTimingRepository.save(usersLearnTimingDO);

        //添加延迟push推送，如果用户不在线触发push
        LeaveMsgVO leaveMsg = LeaveMsgVO.builder().userId(usersLearnTimingDO.getUserId().intValue()).startLearnTime(startTime.getTime()).uniqueId(UUID.randomUUID().toString()).build();
        usersStudyService.addLeaveMsg(leaveMsg);

        commonTaskExecutor.execute(() -> friendMessageNotice(userId));
    }


    private void friendMessageNotice(Long userId) {
        List<UsersVO> onlineFriends = usersService.findOnlineFriend(userId);
        if (onlineFriends.isEmpty()) {
            log.debug("用户专注计时-没有在线的道友和关注他的人，不发送消息 userId = {}", userId);
            return;
        }

        onlineFriends.forEach(friend -> {
            ShareMsgParamVO message = ShareMsgParamVO.builder()
                    .type(TIME_LEARN_ROOM_TAKE_SEAT_NOTICE.getType())
                    .fromUserId(userId.toString())
                    .toId(friend.getId().toString())
                    .realToId(friend.getId())
                    .message("用户开始专注计时")
                    .build();
            log.info("用户专注计时-开始学习： message = {}", message);
            socketService.sendMessage(message);
        });

    }
}
